package com.trgis.qtmap.community.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mongodb.DBObject;
import com.trgis.qtmap.community.modle.ColumnMeta;
import com.trgis.qtmap.community.modle.TableMeta;
import com.trgis.qtmap.community.service.SchemaManagementService;
import com.trgis.qtmap.data.mongodb.TRMongoRepository;
import com.trgis.qtmap.data.mybatis.dao.ColumnMetaDAO;
import com.trgis.qtmap.data.mybatis.dao.TableMetaDAO;

@Service
public class SchemaManagementServiceImpl implements SchemaManagementService {

	@Autowired
	private TableMetaDAO tableMetaDAO;

	@Autowired
	private ColumnMetaDAO columnMetaDAO;

	@Autowired
	private TRMongoRepository trMongoRepository;

	@Override
	public void insertTable(TableMeta tableMeta) {
		trMongoRepository.createCollection(tableMeta.getMongoCollectionName());
		tableMetaDAO.insertTableMeta(tableMeta);
		Long tableMetaId = tableMeta.getId();
		if (tableMeta.getColumns() != null) {
			for (int i = 0; i < tableMeta.getColumns().size(); i++) {
				ColumnMeta cm = tableMeta.getColumns().get(i);
				cm.setTableMeta(tableMetaId);
				columnMetaDAO.insert(cm);
			}
		}
	}

	@Override
	public List<TableMeta> findAllTable() {
		return tableMetaDAO.findAll();
	}

	@Override
	public void deleteTableSchema(Long id) {
		TableMeta tm = tableMetaDAO.findOne(id);
		String collectionName = tm.getMongoCollectionName();
		columnMetaDAO.deleteTableColumns(id);
		tableMetaDAO.deleteTableMeta(id);
		trMongoRepository.dropCollection(collectionName);
	}

	@Override
	public TableMeta findOneTable(Long id) {
		return tableMetaDAO.findOne(id);
	}

	@Override
	public void insertColumn(ColumnMeta columnMeta) {
		columnMetaDAO.insert(columnMeta);
	}

	@Override
	public TableMeta getForm(Long id) {
		return tableMetaDAO.findOne(id);
	}

	@Override
	public void saveDataToMongo(String mongoCollectionName, DBObject data) {
		trMongoRepository.insert(mongoCollectionName, data);
	}

}